#include "DXEngineInput.h"
#include <dxerr.h>


CDXEngineInput::CDXEngineInput()
{
	ZeroMemory(m_KeyboardState, sizeof(m_KeyboardState));
	ZeroMemory(&m_MouseState, sizeof(m_MouseState));
	ZeroMemory(&m_MousePosition, sizeof(m_MousePosition));
	m_HWin = NULL;
}


CDXEngineInput::~CDXEngineInput()
{
	ReleaseCOM(m_DInput);
	m_Keyboard->Unacquire();
	m_Mouse->Unacquire();
	ReleaseCOM(m_Keyboard);
	ReleaseCOM(m_Mouse);
}



bool CDXEngineInput::Init(HINSTANCE appInst, HWND hWin, DWORD keyboardCoopFlags, DWORD mouseCoopFlags)
{
	m_HWin = hWin;
	HR(DirectInput8Create(appInst, DIRECTINPUT_VERSION, 
		IID_IDirectInput8, (void**)&m_DInput, 0));
	HR(m_DInput->CreateDevice(GUID_SysKeyboard, &m_Keyboard, 0));
	HR(m_Keyboard->SetDataFormat(&c_dfDIKeyboard));
	HR(m_Keyboard->SetCooperativeLevel(hWin, keyboardCoopFlags));
	HR(m_Keyboard->Acquire());
	HR(m_DInput->CreateDevice(GUID_SysMouse, &m_Mouse, 0));
	HR(m_Mouse->SetDataFormat(&c_dfDIMouse2));
	HR(m_Mouse->SetCooperativeLevel(hWin, mouseCoopFlags));
	HR(m_Mouse->Acquire());
	return true;
}



void CDXEngineInput::Poll()
{	
	HRESULT hr = S_OK;

	hr = m_Keyboard->GetDeviceState(sizeof(m_KeyboardState), (void**)&m_KeyboardState);
	if( FAILED(hr) )
	{
		ZeroMemory(m_KeyboardState, sizeof(m_KeyboardState));
		hr = m_Keyboard->Acquire();
	}
	hr = m_Mouse->GetDeviceState(sizeof(DIMOUSESTATE2), (void**)&m_MouseState); 
	if( FAILED(hr) )
	{
		ZeroMemory(&m_MouseState, sizeof(m_MouseState));
		hr = m_Mouse->Acquire(); 
	}
	GetCursorPos(&m_MousePosition);
	ScreenToClient(m_HWin, &m_MousePosition);
}



